package com.haoyu.number.Demo.array;

/**
 * @author 蒿雨
 * @create 2021-10-28 10:06
 * 稀疏数组练习(掌握)
 */
public class SparseArrayTest {
    public static void main(String[] args) {
        //创建一个二维数组
        int arr02[][] = new int[10][10];
        arr02[2][3] = 1;
        arr02[3][4] = 2;
        arr02[4][5] = 3;
        System.out.println("原始的二维数组");
        //输出数组
        for (int[] ints : arr02) {
            for (int anInt : ints) {
                System.out.printf("%d\t", anInt);
            }
            System.out.println("");
        }
        //求出有效数据的个数
        int count = 0;
        for (int i = 0; i < arr02.length; i++) {
            for (int j = 0; j < arr02.length; j++) {
                if (arr02[i][j] != 0) {
                    count++;
                }
            }
        }
        System.out.printf("有效个数为：%d", count);
        System.out.println();
        //给稀疏数组赋值
        int arrX[][] = new int[count + 1][3];
        //得到稀疏数组
        arrX[0][0] = 11;
        arrX[0][1] = 11;
        arrX[0][2] = count;

        int index = 0;
        for (int i = 0; i < arr02.length; i++) {
            for (int j = 0; j < arr02.length; j++) {
                if (arr02[i][j] != 0) {
                    index++;
                    arrX[index][0] = i;
                    arrX[index][1] = j;
                    arrX[index][2] = arr02[i][j];
                }
            }
        }
        for (int i = 0; i < arrX.length; i++) {
            System.out.printf("第%d\t行,第%d\t列，值是%d\n",arrX[i][0],arrX[i][1],arrX[i][2]);
        }
        //还原稀疏数组
        int arr03 [][] = new int[arrX[0][0]][arrX[0][1]];
        //循环把值付给二维数组
        for (int i = 1; i < arrX.length; i++) {
            arr03[arrX[i][0]][arrX[i][1]]=arrX[i][2];
        }
        //展示二维数组的结果
        for (int[] ints : arr03) {
            for (int anInt : ints) {
                System.out.printf("%d\t\t",anInt);
            }
            System.out.println();
        }

    }
}


